package com.mes.cloud.service.impl;

import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import com.mes.cloud.enums.ValidatorMsgEnums;
import com.mes.cloud.service.ValidatorService;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @ProjectName: cloud
 * @Package: com.mes.cloud.service.impl
 * @ClassName: MatchValidatorServiceImpl
 * @Author: xhy
 * @Description: 判断view页面输入值和该字段本身的值得比较一般有
 * match[field]//表示于field字段的值匹配
 * match[<field]//表示小于field字段的值
 * match[<=field]//表示小于等于field字段的值
 * match[==field]//表示等于field字段的值
 * match[>=field]//表示大于等于field字段的值
 * match[>field]//表示大于field字段的值
 * @Date: 2019年9月23日15:17:54
 * @Version: 1.0
 */
@Service("match")
public class MatchValidatorServiceImpl implements ValidatorService {
    private static final Pattern PATTERN = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
    @Override
    public String validator(@NotNull String type,@NotNull Object o, Map<String, Object> queryMap){
        String methodName = type.toLowerCase();
        int subLegtn = methodName.indexOf("[") ;
        String valiMsg= methodName.substring(0, subLegtn);
        Matcher matcher = PATTERN.matcher(methodName);
        String matcherMethod="";
        while (matcher.find()){
            matcherMethod=matcher.group().trim();
        }
        String tagerMsg = matcherMethod;
        int filedInt;
        if (matcherMethod.contains("=<") || matcherMethod.contains(">=") || matcherMethod.contains("==")){
            filedInt = 3;
        }else {
            filedInt = 2;
        }
        String filed = matcherMethod.substring(filedInt);
        matcherMethod.replace(filed,queryMap.get(filed).toString());
        Map<String, Object> env = Maps.newHashMap();
        env.put("x",o.toString());
        boolean flage = (Boolean) AviatorEvaluator.compile(matcherMethod).execute(env);
        return flage==true? null: MessageFormat.format(ValidatorMsgEnums.getDesc(valiMsg),filed);
    }
}
